<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-dtl', title: '备货明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">备货信息</div>
          <customFormItem
            label="备货申请单" name="oprtApplyKey" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="$refs.tableDrawerApplySelect.show()"
            :disabled="!propParent.cpFormNew"
            help="保存后不可修改"
          />

          <customFormItem
            label="备货日期" name="prepareDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
            disabled
          />
          <customFormItem
            label="备货单号" name="prepareKey" :parent="_self" :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            disabled
          />
          <customFormItem label="备货类型" name="prepareType" :parent="_self" :form="form"
              :type="constCommon.formItemType.selectDict.name" :config="{dictType: constCommon.dictType.oprtApplyType}"
                          disabled
          />

          <customFormItem
            label="备货仓库" name="warehouseNameFrom" :parent="_self" :form="form"
            disabled
          />

          <customFormItem
            label="配送仓库" name="warehouseName" :parent="_self" :form="form"
            disabled
          />

          <customFormItem
            label="手术单号" name="oprtCode" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="手术日期" name="oprtDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="患者" name="patientName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="utilSelect.patient(patientChange)"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="患者年龄" name="patientAge" :parent="_self" :form="form"  :type="constCommon.formItemType.inputNumber.name"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="床位号" name="bedNo" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="住院编号" name="patientNo" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="主治医生" name="docNameSug" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="专家" name="docNameApply" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem label="备注" name="remark"  :parent="_self" :form="form" />
        </template>
      </customForm>
      <div id="box-dtl" class="box-title">备货明细</div>
      <customTooltip title="title" v-show="!propReadonly && !propParent.cpFormNew">
        <template #title>
          选择库存或者扫描相关标签码
        </template>
        <template #content>
          <FortenScan ref="scan" propPlaceholder="扫描唯一码" style="width: 300px;margin-top: 10px;display: inline-block; margin-right: 5px" @after-scan="barCodeScan" propType="uniqueCode"/>
          <customButton title="选择库存" theme="primary" @click="utilSelect.stockMore(selectChangeStock, form.warehouseId, null, true,  true, null, null, null,'1')" />
        </template>
      </customTooltip>
      <data-view
        propViewKey="wm_oprt_prepare_item"
        :propInitData="form"
        ref="childDataView"
        :propNoEditRow="true"
        :propHideFlowSelect="true"
        :propFlowKey="propParent.propFlowKey"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propParentData="propParent.viewFormData"
        :propTableHide="propParent.cpFormNew"
        propTableHideMsg="请先保存主单据再操作"
      />
    </div>

    <!--备货申请单选择-->
    <tableDrawer ref="tableDrawerApplySelect" refName="tableDrawerApplySelect"
                 @confirm="tableDrawerApplySelectChange"
                 viewKey="dept_oprt_apply_select"
                 subtitle="已审核尚未进行跟台备货的备货申请单(术间、手术)"
    />
  </div>
</template>

<script>
import barcodeParse from '@/util/barcodeParse'
import stockSelect from '@/components/base/popover/StockSelect.vue'
import packSelect from '@/components/base/PackSelect.vue'
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      txtScan: '',
      formReadOnly: false, //是否只读
      propPackType: 'oper_apply',
      stockDialogVisible: false
    }
  },
  methods: {
      // 加载明细数据
      fetchChildData() {
        let queryWrapper = this.$newWrapper()
        if (this.form.id) {
          queryWrapper.eq('prepareId', this.form.id)
        } else {
          queryWrapper.ne(1, 1)
        }
        this.$refs.childDataView.setQueryWrapper(queryWrapper)
      },
    childRowEdit() {
      this.utilMessage.warning('当前耗材已锁库！不能编辑')
      this.$refs.childDataView.fetchData()
      return false
    },
    handleChangeApply(key) {
      for (const s1 of this.propDictionaries.oprtApplyId.filter(s => this.form.oprtApplyId == s.id)) {
        this.$set(this.form, 'oprtId', s1.oprtId)
        this.$set(this.form, 'oprtName', s1.oprtName)
        this.$set(this.form, 'oprtCode', s1.oprtCode)
        this.$set(this.form, 'oprtDate', s1.oprtDate)
        this.$set(this.form, 'patientId', s1.patientId)
        this.$set(this.form, 'patientName', s1.patientName)
        this.$set(this.form, 'patientAge', s1.patientAge)
        this.$set(this.form, 'patientNo', s1.patientNo)
        this.$set(this.form, 'bedNo', s1.bedNo)
        this.$set(this.form, 'docNameSug', s1.docNameSug)
        this.$set(this.form, 'docNameApply', s1.docNameApply)
        let params = {
          oprtApplyId: key,
          id: this.form.id
        }
      }
    },
    getChildQueryWrapper() {
      if (this.form.id) {
        return this.$newWrapper().eq('prepareId', this.form.id).eq('matr_type', '1')
      } else {
        return this.$newWrapper().ne(1, 1)
      }
    },
    deleteMatr(row) {
      this.$confirm('此操作将永久删除该跟台包及包内耗材, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$ajax.delete('/wm/oprt_prepare_item/deleteMatr', { params: { id: row.id } })
          .then(response => {
            this.utilMessage.success('删除成功!')
            this.fetchData()
          })
      }).catch(() => {
        this.utilMessage.info('已取消删除')
      })
    },
    deletePackage(row) {
      this.$confirm('此操作将永久删除该跟台包及包内耗材, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$ajax.delete('/wm/oprt_prepare_item/deletePackage', { params: { id: row.id } })
          .then(response => {
            this.utilMessage.success('删除成功!')
            this.fetchData()
          })
      }).catch(() => {
        this.utilMessage.info('已取消删除')
      })
    },
    async addPackage() {
      if (!this.form.id) {
        await this.propParent.ocAsynSaveViewForm()
      }
      this.stockDialogVisible = true
    },
    oprtChange(key) {
      let params = {
        oprtApplyId: key,
        id: this.form.id
      }
      this.$ajax.post('/wm/oprt_prepare_item/addByOprtApply', params).then((resp) => {
        this.fetchData()
      })
    },
    handleChangeOprt(value) {
      if (!value) {
        return
      }
      let params = { id: value }
      this.$ajax.get('/base/oprt/getOprtById', { params }).then((resp) => {
        let data = resp.data
        this.$set(this.form, 'oprtCode', data.code)
        this.$set(this.form, 'patientName', data.patientName)
        this.$set(this.form, 'patientAge', data.patientAge)
        this.$set(this.form, 'bedNo', data.bedNo)
        this.$set(this.form, 'patientNo', data.inpatientNo)
        this.$set(this.form, 'oprtDate', data.date)
        this.$set(this.form, 'docNameApply', data.doctorNameApply)
        this.$set(this.form, 'docNameSug', data.doctorNameSug)
      })
    },
    extraButtonClick({ button, data, index }) {
      let { key: buttonKey } = button
      if (buttonKey === 'oprtBagSelect') {
        this.stockDialogVisible = true
      }
    },
    confirmCheck(rows) {
      this.stockDialogVisible = false
      if (!rows.length) {
        return
      }
      let codeType = barcodeParse.barCodeType(rows[0].sn)
      let params = {
        'prepareId': this.form.id,
        'uniqueCode': rows[0].sn,
        'warehouseId': this.form.warehouseId
      }
      if (codeType == 'SN') {
        this.$ajax.post('/wm/oprt_prepare_item/addPrepareItem', params).then(resp => {
          this.fetchData()
        })
      } else {
        this.utilMessage.error('SN格式不正确')
      }
      this.fetchData()
    },
    //扫码SN或RFID
    barCodeScan(scanValue) {
      let params = {
        'prepareId': this.form.id,
        'uniqueCode': scanValue,
        'warehouseId': this.form.warehouseId
      }

      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/oprt_prepare_item/addScan', params).then(resp => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg, 2000)
          this.fetchChildData()
        }
      })
    },
    fetchData() {
      this.$refs.childDataView.fetchData()
    },

    // 备货申请单选择
    tableDrawerApplySelectChange(row) {
      this.$set(this.form, 'prepareType', row.oprtApplyType)
      this.$set(this.form, 'oprtApplyId', row.id)
      this.$set(this.form, 'oprtApplyKey', row.oprtApplyKey)
      // 备货仓库
      this.$set(this.form, 'warehouseIdFrom', row.warehouseIdFrom)
      this.$set(this.form, 'warehouseNameFrom', row.warehouseNameFrom)

      // 配送仓库
      this.$set(this.form, 'warehouseId', row.warehouseIdTo)
      this.$set(this.form, 'warehouseName', row.warehouseNameTo)
      this.$set(this.form, 'oprtId', row.oprtId)
      this.$set(this.form, 'oprtName', row.oprtName)
      this.$set(this.form, 'oprtCode', row.oprtCode)
      this.$set(this.form, 'oprtDate', row.oprtDate)
      this.$set(this.form, 'patientId', row.patientId)
      this.$set(this.form, 'patientName', row.patientName)
      this.$set(this.form, 'patientAge', row.patientAge)
      this.$set(this.form, 'patientNo', row.patientNo)
      this.$set(this.form, 'bedNo', row.bedNo)
      this.$set(this.form, 'docNameSug', row.docNameSug)
      this.$set(this.form, 'docNameApply', row.docNameApply)
    },
    //库存选择后
    selectChangeStock(rows) {
      rows.forEach(row => {
        row.prepareId = this.form.id
        row.stockId = row.id
      })

      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/oprt_prepare_item/addBatch', rows).then(resp => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg, 2000)
          this.fetchChildData()
        }
      })
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          this.$set(this.form, 'prepareDate', new Date().format(this.dates.defaultDatePattern))
        }
        this.fetchChildData()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (valueTo) => {
      },
      beforeClose: () => {
        return true
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {
    stockSelect,
    packSelect,
    customAnchor
  },
  computed: {
    // 是否是手术备货申请
    cpIsOprtApplyType1() {
      return this.form.prepareType == this.constCommon.dictType.oprtApplyTypeOprt
    }
  }
}
</script>
